/**
 * Shift form for AJAX form submit convenience
 * ==================================================
 * Author: lute
 * ==================================================
 * use case:
 * $('form').shiftform({
 *   loadingMessage: '加载提示',    // 可选，默认为“正在提交表单...”
 *   successMessage: '提交成功信息',   // 可选，默认为“表单提交成功”，优先显示服务器返回的成功信息
 *   failureMessage: '提交失败信息',   // 可选，默认为“表单提交失败”，优先显示服务器返回的业务失败信息
 *   errorMessage:  '提交出错信息',   //  可选，默认为“表单提交出错”，表示提交非业务出错信息
 *   beforeSubmit:    function(el) { // 通常做表单校验 },    // 可选，Ajax提交前执行函数
 *   needLoad: true                // 是否刷新
 *   success: function(el, backdrop, message) { // 提交成功callback },    // 可选
 *            string   selector-triggerEvent                            // 可选
 *   failure: function(el, backdrop, message) { // 提交失败callback }    // 可选
 * })
 */
!function(root, factory) {
  if(typeof define == 'function' && define.amd) {
    define(['jquery'], factory)
  } else if(typeof exports == 'object') {
    factory(require('jquery'))
  } else {
    factory(root.jQuery)
  }
}(this, function($) {
  'use strict';

  $.fn.shiftform = function(option) {

    var options = $.extend({
      loadingMessage: '正在提交表单...',
      successMessage: '表单提交成功',
      failureMessage: '表单提交失败',
      errorMessage: '表单提交出错',
      beforeSubmit: null,
      needLoad: true,
      success: null,
      failure: null,
    },option)

    var backdrop = '<div class="shiftform-backdrop">' +
                     '<div class="backdrop-content">' +
                       '<p><span class="icon icon-loader"></span>' +
                        options.loadingMessage +
                       '</p>' +
                     '</div>' +
                   '</div>'

    function checkForm(el) {
      if(el.tagName.toUpperCase() != 'FORM') return
      var $form = $(el)
      // set form position relative
      $form.css('position', 'relative')

      var startSubmit = function(e) {
        e.preventDefault()
        if(e.target != e.currentTarget) return
        if(!options.beforeSubmit || options.beforeSubmit.call(this, el)) {

          // serialize parameters
          var parameters = $form.serializeArray()

          // disable submit button
          $(e.target).attr('disabled', 'disabled')

          // display backdrop first
          var $backdrop = $(backdrop).appendTo($form)
          
          // calculate backdrop content position
          var backdropHeight = $backdrop.height()
          
          // backdrop message content's default height is 30px and its default margin top is -120px
          if(backdropHeight / 2 - 135 < 0) {
            // this indicates backdrop content's top border goes beyond backdrop's top border
            
            // check backdrop height is smaller than message default height
            if(backdropHeight < 30) {
              // If yes, reset message height and position
              $backdrop.find('.backdrop-content').height(backdropHeight - 20)
                                                 .css('margin-top', '-' + ((backdropHeight - 20) / 2) + 'px')
            } else {
              // Just reset message top margin
              $backdrop.find('.backdrop-content').css('margin-top',  '-' + (backdropHeight / 2 - 15) + 'px')
            }
          }
          
          // 成功之后跳转页面（无弹出框）
          var changeBackdropRedirect = function(message, clazz, callback, url) {
            if(callback && typeof callback === 'function') {
              
              callback(el, $backdrop[0], message)
              setTimeout(function() {
                if($form.data("redirect")){
                  window.location.href = $form.data("redirect");
                } else if ($form.data("anchor")) {
                  var currentUrl = window.location.href;
                  if (currentUrl.indexOf('#anchor') >= 0) {
                    currentUrl = currentUrl.substring(0, currentUrl.indexOf('#anchor'));
                  }
                  currentUrl = currentUrl.indexOf('?') >= 0 ? (currentUrl + '&random=' + new Date() + $form.data("anchor")) : (currentUrl + '?random=' + new Date() + $form.data("anchor"));
                  window.location.replace(currentUrl);
                } else if(url) {
                  window.location.href = window.__CTX__.root + url;
                } else if(options.needLoad) {
                  window.location.reload() 
                }
              }, 1000)
              
            } else if(callback && typeof callback === 'string') {
              $backdrop.find('p').html('<strong>' + message + '</strong>').addClass(clazz ? clazz : '')
              $($form.parents(".modal")).modal('hide');
              $(callback.split('-')[0]).trigger(callback.split('-')[1]);
            }else {
              if($form.data("redirect")){
                window.location.href = $form.data("redirect");
              } else if ($form.data("anchor")) {
                var currentUrl = window.location.href;
                if (currentUrl.indexOf('#anchor') >= 0) {
                  currentUrl = currentUrl.substring(0, currentUrl.indexOf('#anchor'));
                }
                currentUrl = currentUrl.indexOf('?') >= 0 ? (currentUrl + '&random=' + new Date() + $form.data("anchor")) : (currentUrl + '?random=' + new Date() + $form.data("anchor"));
                window.location.replace(currentUrl);
              } else if(url) {
                window.location.href = window.__CTX__.root + url;
              } else if(options.needLoad) {
                window.location.reload()
              }
            }
          }
          
          // function for changing backdrop display mesage
          var changeBackdropMessage = function(message, clazz, callback, url) {
                               
            console.log(typeof callback);
            if(callback && typeof callback === 'function') {
              
              callback(el, $backdrop[0], message)
              setTimeout(function() {
                if($form.data("redirect")){
                  window.location.href = $form.data("redirect");
                } else if ($form.data("anchor")) {
                  var currentUrl = window.location.href;
                  if (currentUrl.indexOf('#anchor') >= 0) {
                    currentUrl = currentUrl.substring(0, currentUrl.indexOf('#anchor'));
                  }
                  currentUrl = currentUrl.indexOf('?') >= 0 ? (currentUrl + '&random=' + new Date() + $form.data("anchor")) : (currentUrl + '?random=' + new Date() + $form.data("anchor"));
                  window.location.replace(currentUrl);
                } else if(url) {
                  window.location.href = window.__CTX__.root + url;
                } else if(options.needLoad) {
                  window.location.reload() 
                }
              }, 1500)
              
            } else if(callback && typeof callback === 'string') {
              $backdrop.find('p').html('<strong>' + message + '</strong>').addClass(clazz ? clazz : '')
              $($form.parents(".modal")).modal('hide');
              $(callback.split('-')[0]).trigger(callback.split('-')[1]);
            }else {
              $backdrop.find('p').html('<strong>' + message + '</strong>').addClass(clazz ? clazz : '')
              setTimeout(function() {
                if($form.data("redirect")){
                  window.location.href = $form.data("redirect");
                } else if ($form.data("anchor")) {
                  var currentUrl = window.location.href;
                  if (currentUrl.indexOf('#anchor') >= 0) {
                    currentUrl = currentUrl.substring(0, currentUrl.indexOf('#anchor'));
                  }
                  currentUrl = currentUrl.indexOf('?') >= 0 ? (currentUrl + '&random=' + new Date() + $form.data("anchor")) : (currentUrl + '?random=' + new Date() + $form.data("anchor"));
                  window.location.replace(currentUrl);
                } else if(url) {
                  window.location.href = window.__CTX__.root + url;
                } else if(options.needLoad) {
                  window.location.reload()
                }
              }, 1500)
            }
          }
          
          // ajax post data after 1s
          setTimeout(function() {
            $.ajax({
              type: $form.attr('method'),
              url: $form.attr('action'),
              data: parameters
            }).done(function(data) {
            	console.log(data.code);
              data = typeof data === 'String' ? JSON.parse(data) : data
              if(parseInt(data.code) == 0) {  
                changeBackdropRedirect(data.message || options.successMessage, 'text-success', options.success, data.data.url)
              } else {
                changeBackdropMessage(data.message || options.failureMessage, 'text-danger', options.failure, data.data ? data.data.url : null)
              }
            }).fail(function() {
              changeBackdropMessage(options.errorMessage, 'text-danger')
            })
          }, 500)
        }
      }

      $form.on('click', '[type="submit"]', startSubmit)
      
      $form.on('click', '[data-shift-submit="true"]', startSubmit)
      
    }

    return this.each(function() {
      checkForm(this)
    })

  }

  $.fn.shiftform.noConflict = function() {
    $.fn.shiftform = old
    return this
  }

})
